#include "protocol.h"
#include <cstring>
#include <cstdio>
#include <unistd.h>

#ifndef NO_QT
#include <QtDebug>
#endif

int protocol_make_pkt(TPacket& packet, uint8_t type, uint8_t status, uint8_t *data, uint32_t length)
{
	packet.header.head = 0;
	packet.header.head |= (type & P_TYPE_MASK);
	packet.header.head |= ((status << 5) & P_STAT_MASK);
	packet.header.genId = 0;
	packet.header.length = (uint16_t)length;
	packet.data = data;
	packet.length = length;
	return 0;
}

#ifndef NO_QT
int protocol_send_pkt(QTcpSocket *skt, TPacket& packet)
{
	static char buffer[READ_BUFFER_SIZE];
	int count = sizeof(TPacketHeader);

	memcpy(buffer, (uint8_t *)&packet.header, count);
	if(packet.data != NULL){
		memcpy(buffer + count, packet.data, packet.length);
		count += packet.length;
	}

	if(skt->write(buffer, count) != count){
//		qDebug() << "write < count";
		return -1;
	}
//	qDebug() << "protocol_send_pkt: count = " << count;
	return 0;
}
#else
int protocol_send_pkt(int skt, TPacket& packet)
{
	static unsigned char buffer[READ_BUFFER_SIZE];
	int count = sizeof(TPacketHeader);

	memcpy(buffer, (uint8_t *)&packet.header, count);
	if(packet.data != NULL){
		memcpy(buffer + count, packet.data, packet.length);
		count += packet.length;
	}

	if(write(skt, buffer, count) != count){
		perror("write");
		return -1;
	}
	return 0;
}

#endif

int protocol_get_status(const TPacket& packet)
{
	return (((uint8_t)packet.header.head) & P_STAT_MASK) >> 5;
}
